<template>
  <div class="app-container">
    <el-row :gutter="20" v-if="!isStudent">
      <el-col :span="24">
        <el-row :gutter="20" class="kpi-row">
          <el-col :xs="12" :sm="12" :md="6" :lg="6" v-for="card in kpiCards" :key="card.key">
            <el-card class="kpi-card" shadow="hover">
              <div class="kpi-icon" :style="{ background: card.bg }">
                <i :class="card.icon" />
              </div>
              <div class="kpi-meta">
                <div class="kpi-title">{{ card.title }}</div>
                <count-to :start-val="0" :end-val="card.value" :duration="1200" class="kpi-num" />
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="16">
        <el-card class="box">
          <div slot="header" class="clearfix">
            <span>系统概览</span>
            <el-button style="float: right; padding: 3px 0; font-size: 12px" type="text">系统版本：{{ version }}</el-button>
          </div>

          <div class="intro">
            <div class="title" style="padding-top: 0px">系统介绍</div>
            <div v-if="isStudent">
              欢迎来到在线考试中心。这里你可以：
              1）在“在线考试”中参加老师发布的考试；
              2）在“我的错题集”中复盘错题并进行针对性训练；
              3）在“公共题库”中按题库自助练习，提升掌握度。
            </div>
            <div v-else>
              云帆考试系统基于 SpringBoot + Vue 构建，提供在线考试、用户体系、错题训练、考试规则、智能算分等功能。
            </div>

            <div class="title">技术栈</div>
            <div class="tags">
              <el-tag>SpringBoot</el-tag>
              <el-tag>Shiro</el-tag>
              <el-tag>MyBatis Plus</el-tag>
              <el-tag>Redis</el-tag>
              <el-tag>JWT</el-tag>
              <el-tag>Vue2</el-tag>
              <el-tag>ElementUI</el-tag>
            </div>

            <div class="title">产品功能</div>
            <div>
              <div>完善的前后端分离架构与规范接口文档</div>
              <div>基于 Shiro + JWT 的权限体系</div>
              <div>系统配置、用户、部门、角色等基础管理</div>
              <div>题库管理：单选、多选、判断，支持批量导入/导出</div>
              <div>考试范围控制：公开或按部门定向</div>
              <div>在线考试、成绩查看、错题训练</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card>
          <div slot="header">快捷操作</div>
          <div class="quick-grid">
            <router-link v-for="action in quickActions" :key="action.label" :to="action.to" class="quick-item">
              <el-tooltip :content="action.label" placement="top">
                <el-button :type="action.type" plain :icon="action.icon" class="quick-btn">{{ action.label }}</el-button>
              </el-tooltip>
            </router-link>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
  
</template>

<script>
import { mapGetters } from 'vuex'
import CountTo from 'vue-count-to'
import config from '../../../package.json'
import { post } from '@/utils/request'

export default {
  name: 'Dashboard',
  components: { CountTo },
  data() {
    return {
      currentRole: 'adminDashboard',
      version: config.version,
      kpiCards: [
        { key: 'students', title: '学员数量', value: 0, icon: 'el-icon-user', bg: '#E6F7FF' },
        { key: 'repos', title: '题库数量', value: 0, icon: 'el-icon-collection', bg: '#F6FFED' },
        { key: 'questions', title: '试题数量', value: 0, icon: 'el-icon-edit', bg: '#FFF7E6' },
        { key: 'exams', title: '考试场次', value: 0, icon: 'el-icon-data-board', bg: '#FFF0F6' }
      ],
      quickActions: []
    }
  },
  computed: {
    ...mapGetters([
      'roles',
      'siteData'
    ])
    ,
    isStudent() {
      const roles = this.roles || []
      return roles.includes('student') && !roles.includes('sa') && !roles.includes('teacher')
    }
  },
  created() {
    this.updateKpiForStudent()
    this.loadKpis()
    this.buildQuickActions()
  },
  mounted() {
    // 确保页面加载完成后再次尝试加载数据
    this.$nextTick(() => {
      this.loadKpis()
    })
  },
  methods: {
    updateKpiForStudent() {
      if (this.isStudent) {
        // 为学生用户更新KPI卡片标题
        this.kpiCards = [
          { key: 'students', title: '学员数量', value: 0, icon: 'el-icon-user', bg: '#E6F7FF' },
          { key: 'repos', title: '公共题库', value: 0, icon: 'el-icon-collection', bg: '#F6FFED' },
          { key: 'questions', title: '试题数量', value: 0, icon: 'el-icon-edit', bg: '#FFF7E6' },
          { key: 'exams', title: '考试场次', value: 0, icon: 'el-icon-data-board', bg: '#FFF0F6' }
        ]
      }
    },
    async loadKpis() {
      // 如果是学生用户，只加载学生可以访问的数据
      if (this.isStudent) {
        await this.loadStudentData()
        return
      }

      // 管理员用户加载完整统计数据
      try {
        // 学员数量
        const s = await post('/exam/api/sys/user/count-students', {})
        this.setKpi('students', s.data || 0)
      } catch (e) {
        console.log('获取学员数量失败:', e)
      }

      try {
        // 题库数量
        const repo = await post('/exam/api/repo/paging', { current: 1, size: 1 })
        this.setKpi('repos', (repo.data && repo.data.total) || 0)
      } catch (e) {
        console.log('获取题库数量失败:', e)
      }

      try {
        // 试题数量
        const qu = await post('/exam/api/qu/qu/paging', { current: 1, size: 1 })
        this.setKpi('questions', (qu.data && qu.data.total) || 0)
      } catch (e) {
        console.log('获取试题数量失败:', e)
      }

      try {
        // 考试数量（以试卷为统计口径更稳定）
        const paper = await post('/exam/api/paper/paper/paging', { current: 1, size: 1 })
        this.setKpi('exams', (paper.data && paper.data.total) || 0)
      } catch (e) {
        console.log('获取考试数量失败:', e)
      }
    },
    async loadStudentData() {
      // 学生用户只加载公共题库数据
      try {
        const repo = await post('/exam/api/repo/public-paging', { current: 1, size: 1 })
        this.setKpi('repos', (repo.data && repo.data.total) || 0)
      } catch (e) {
        console.log('获取公共题库数量失败:', e)
      }
      
      // 其他数据设为0，因为学生用户不需要这些统计
      this.setKpi('students', 0)
      this.setKpi('questions', 0)
      this.setKpi('exams', 0)
    },
    setKpi(key, val) {
      const idx = this.kpiCards.findIndex(i => i.key === key)
      if (idx > -1) this.$set(this.kpiCards[idx], 'value', Number(val) || 0)
    },
    buildQuickActions() {
      const roles = this.roles || []
      const isStudent = roles.includes('student') && !roles.includes('sa') && !roles.includes('teacher')
      const isAdmin = roles.includes('sa')
      
      if (isStudent) {
        this.quickActions = [
          { label: '在线考试', to: { path: '/my/exam' }, icon: 'el-icon-guide', type: 'primary' },
          { label: '我的错题集', to: { path: '/wrong-book/index' }, icon: 'el-icon-document', type: 'warning' },
          { label: '公共题库', to: { path: '/public-repo/index' }, icon: 'el-icon-collection', type: 'success' }
        ]
      } else if (isAdmin) {
        // 超级管理员显示所有功能包括系统配置
        this.quickActions = [
          { label: '考试管理', to: { path: '/exam/exam' }, icon: 'el-icon-data-board', type: 'primary' },
          { label: '题库管理', to: { path: '/exam/repo' }, icon: 'el-icon-collection', type: 'success' },
          { label: '试题管理', to: { path: '/exam/qu' }, icon: 'el-icon-edit', type: 'warning' },
          { label: '系统配置', to: { path: '/sys/config' }, icon: 'el-icon-setting', type: 'info' }
        ]
      } else {
        // 教师等其他角色不显示系统配置
        this.quickActions = [
          { label: '考试管理', to: { path: '/exam/exam' }, icon: 'el-icon-data-board', type: 'primary' },
          { label: '题库管理', to: { path: '/exam/repo' }, icon: 'el-icon-collection', type: 'success' },
          { label: '试题管理', to: { path: '/exam/qu' }, icon: 'el-icon-edit', type: 'warning' }
        ]
      }
    }
  }
}
</script>

<style scoped>
.box{
  height: calc(100vh - 120px);
  font-size: 14px;
  line-height: 28px;
}
.intro{ line-height: 32px; }
.title{
  font-size: 18px;
  font-weight: 700;
  padding-bottom: 10px;
  padding-top: 20px;
  margin-bottom: 10px;
  border-bottom: #eee 1px dotted;
}

.tags span{
  margin-right: 10px;
}

.box a{
  color: #20a0ff;
}

.box a:hover{
  color: #ff0000;
}

.kpi-row{ margin-bottom: 10px; }
.kpi-card{ display: flex; align-items: center; }
.kpi-icon{ width: 46px; height: 46px; border-radius: 8px; display: flex; align-items: center; justify-content: center; margin-right: 12px; }
.kpi-icon i{ font-size: 22px; color: #2c3e50; }
.kpi-meta{ flex: 1; }
.kpi-title{ color: #909399; font-size: 12px; }
.kpi-num{ font-size: 22px; font-weight: 700; }
.quick-grid{ display: grid; grid-template-columns: repeat(2, 1fr); grid-gap: 10px; }
.quick-item{ width: 100%; }
.quick-btn{ width: 100%; }
</style>
